import os
import sys
import copy

from command_parser.command_generate import GenCommand
from command_parser.ar_parse.ar_option_filter import ARFilter

class ARGenCommand(GenCommand):
    
    def __init__(self, context=None, cwd=""):
        self.context = context
        self.cwd = cwd
        self.filter = ARFilter(context=context)
    
    def ast_to_mpl(self, ast_path=""):
        if not ast_path:
            raise Exception("Lack of ast file when getting mpl path")
        
        md5_str = os.path.splitext(os.path.basename(ast_path))[0]
        mpl_path = os.path.join(self.context.MAPLE_DIR, md5_str + self.context.MAPLE_EXT)
        
        return mpl_path
    
    def generate_maple_link_command(self, compiler="", input_options=[], output_option=None):
        
        if not compiler or not input_options or not output_option:
            return
        
        if self.context.IR_CAT_MODE:
            return self.get_maple_ir_cat_command(input_options, output_option)
        
        input_files = []
        for opt in input_options:
            if opt.keep:
                input_files.extend(opt.parameter)
        
        output_file = output_option.parameter[0]
        command = [compiler, "-wpaa"]
        command.extend(input_files)
        command.extend(["-o", output_file])
        command.append("--enable-variable-array")
        
        return command
    
    
    def get_maple_ir_cat_command(self, input_options=[], output_option=None):
        input_files = []
        
        for opt in input_options:
            if opt.keep:
                input_files.extend([self.ast_to_mpl(file) for file in opt.parameter])
        
        output_file = output_option.parameter[0]
        
        sub_cmd = "cat {} >> {}".format(' '.join(input_files), output_file)
        
        command = ["sh", "-c", sub_cmd]
        
        return command
        
        
        
        